﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Caching.Memory;

namespace Common.Cache
{
    public class RuntimeCache : ICache
    {
        private readonly IMemoryCache _cache;
        public RuntimeCache(IMemoryCache cache)
        {
            _cache = cache;
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(object key)
        {
            try
            {
                var result = _cache.Get<T>(key);
                if (result != null)
                {
                    return result;
                }
                return default(T);
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key"></param>
        public void Remove(object key)
        {
            try
            {
                _cache.Remove(key);
            }
            catch
            {
            }
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="cache"></param>
        /// <returns></returns>
        public T Set<T>(object key, T cache)
        {
            try
            {
                _cache.Set(key, cache);
                return cache;
            }
            catch
            {
                return cache;
            }
        }
    }
}
